package com.michaellou.shell;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.util.logging.Level;

import java.util.logging.Logger;

/**
 * 
 * 
 * 
 * @author Wei.Liu
 */

public class Shell2 {

	private Process pro = null;

	private Runtime runTime = null;

	public Shell2() {

		runTime = Runtime.getRuntime();

		if (runTime == null) {

			System.err.println("Create runtime false!");

			System.exit(1);

		}

	}

	public void execueteCommand(String command) throws InterruptedException {

		System.out.println("************************");

		System.out.println("Execute command :" + command);

		System.out.println("Result:");

		try {

			pro = runTime.exec(command);

			BufferedReader input = new BufferedReader(new InputStreamReader(pro
					.getInputStream()));// 这个输入流是获取shell输出的

			PrintWriter output = new PrintWriter(new OutputStreamWriter(pro
					.getOutputStream()));// 这个输出流主要是对Process进行输入控制用的

			String line;

			while ((line = input.readLine()) != null) {

				System.out.println(line);

				if (-1 != line.indexOf("your name")) {// 当检测到提示输入时,则执行输入操作

					output.print("liuwei\r\n");// \r\n 不可少,否则相当于没有Enter操作

					output.flush();// 输入完成之后一定要flush.否则一直处在等待输入的地方

				}

			}

			System.out.println("************************\n");

			input.close();

			output.close();

			pro.destroy();

		} catch (IOException ex) {

			Logger.getLogger(Shell.class.getName()).log(Level.SEVERE, null, ex);

		}

	}

	// //
	public static void main(String args[]) {
		Shell2 p1 = new Shell2();
		Shell2 p2 = new Shell2();
		try {
//			p1.execueteCommand("wget -i /home/edison/桌面/list");
//			p2.execueteCommand("wget http://www.baidu.com");
//			p1.execueteCommand("cmd /k start dir");
			p2.execueteCommand("cmd /k start tree");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}